import { login, setUserInfo, userPhoto } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'
import { resetRouter } from '@/router'
export default {
  namespaced: true,
  state: {
    token: getToken() || '',
    userinfo: {}
  },
  mutations: {
    setToken(state, token) {
      state.token = token
      setToken(token)
    },
    delToken(state) {
      state.token = ''
      removeToken()
    },
    setInfo(state, info) {
      state.userinfo = info
    },
    delInfo(state) {
      state.userinfo = {}
    }
  },
  actions: {
    async userLogin(context, payload) {
      const data = await login(payload)
      console.log(data)
      context.commit('setToken', data.data)
      setTimeStamp()
    },
    async setUserInfo(context) {
      try {
        const { data } = await setUserInfo()
        console.log(data)
        const info = await userPhoto(data.userId)
        console.log(info, 'info')
        context.commit('setInfo', { ...data, ...info.data })
        return data.roles.menus
      } catch (error) {
        console.log('获取用户信息失败')
      }
    },
    userLayout(context) {
      context.commit('delToken')
      context.commit('delInfo')
      // 重置路由
      resetRouter()
    }
  }
}
